'use strict';

const path = require('path');
const webpack = require('webpack');

const ManifestPlugin = require('webpack-manifest-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const LoadablePlugin = require('@loadable/webpack-plugin');

const config = require('./env');
const utils = require('../utils');

const DEV_MODE = config.isDevMode();
const isHMREnabled = config.isHMREnabled();
const isSSREnabled = config.isSSREnabled();

const webpackConfig = {
  resolve: {
    extensions: ['.js', '.vue', '.ts', '.json'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            // This is a feature of `babel-loader` for webpack (not Babel itself).
            // It enables caching results in ./node_modules/.cache/babel-loader/
            // directory for faster rebuilds.
            cacheDirectory: true,
            // See #6846 for context on why cacheCompression is disabled
            cacheCompression: false,
            compact: false,
          },
        },
      },
    ],
  },
  plugins: [
    //in HMR, do not clean built files
    ...(isHMREnabled ? [] : [new CleanWebpackPlugin({ verbose: false })]),
    new webpack.DefinePlugin({
      __isBrowser__: true,
      __HMR__: isHMREnabled,
      __SSR__: isSSREnabled,
      'process.env.DEV_MODE': DEV_MODE,
      'process.env.NODE_ENV': JSON.stringify(config.getNodeEnv()),
    }),

    new CopyWebpackPlugin([
      {
        from: utils.resolve('app/assets/static'),
        to: utils.resolve('build/app/assets/static'),
      },
    ]),
    new LoadablePlugin({
      filename: 'loadable-stats.json',
      writeToDisk: {
        filename: utils.resolve('build/'),
      },
    }),
    new ManifestPlugin({
      publicPath: '',
    }),
    // new HtmlWebpackCustomPlugin(),
  ],
};

module.exports = webpackConfig;
